<template>
  <div class="dashboard-page">
    <!-- 统计卡片区域 -->
    <div class="mb10">
    <div class="stats-grid">
      <div class="stat-item animate-on-enter">
        <div class="stat-icon user-icon">
          <user-outlined />
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ statistics.users?.total || 0 }}</div>
          <div class="stat-label">总用户数</div>
          <div class="stat-trend" :class="getGrowthClass(statistics.users?.growth_rate)">
            <arrow-up-outlined v-if="statistics.users?.growth_rate > 0" />
            <arrow-down-outlined v-if="statistics.users?.growth_rate < 0" />
            {{ Math.abs(statistics.users?.growth_rate || 0) }}%
          </div>
        </div>
      </div>

      <div class="stat-item animate-on-enter animate-delay-1">
        <div class="stat-icon active-icon">
          <team-outlined />
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ statistics.users?.active || 0 }}</div>
          <div class="stat-label">活跃用户</div>
          <div class="stat-desc">今日新增 {{ statistics.users?.today || 0 }}</div>
        </div>
      </div>

      <div class="stat-item animate-on-enter animate-delay-2">
        <div class="stat-icon log-icon">
          <file-text-outlined />
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ statistics.logs?.total || 0 }}</div>
          <div class="stat-label">操作日志</div>
          <div class="stat-desc">成功率 {{ statistics.logs?.success_rate || 0 }}%</div>
        </div>
      </div>

      <div class="stat-item animate-on-enter animate-delay-3">
        <div class="stat-icon admin-icon">
          <crown-outlined />
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ statistics.admins?.active || 0 }}</div>
          <div class="stat-label">管理员</div>
          <div class="stat-desc">总计 {{ statistics.admins?.total || 0 }}</div>
        </div>
      </div>
    </div>
  </div>

  <!-- 图表和信息区域 -->
  <div class="mb10">
    <a-row :gutter="10">
      <!-- 用户增长趋势 -->
      <a-col :xs="24" :lg="16">
        <a-card title="用户增长趋势" class="chart-card animate-on-enter animate-delay-4">
          <div class="chart-container" ref="userGrowthChart"></div>
        </a-card>
      </a-col>

      <!-- 用户分布 -->
      <a-col :xs="24" :lg="8">
        <a-card title="用户分布" class="chart-card animate-on-enter animate-delay-5">
          <div class="chart-container" ref="userDistributionChart"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>

  <!-- 最近日志和系统信息 -->
  <div class="mb10">
    <a-row :gutter="10">
      <!-- 最近操作日志 -->
      <a-col :xs="24" :lg="16">
        <a-card title="最近操作日志" class="logs-card animate-on-enter animate-delay-4" :bordered="false">
          <a-table :columns="logColumns" :data-source="recentLogs" :pagination="false" size="small"
            :scroll="{ x: 800 }">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'is_success'">
                <a-tag :color="record.is_success ? 'success' : 'error'">
                  {{ record.is_success ? '成功' : '失败' }}
                </a-tag>
              </template>
              <template v-if="column.key === 'method'">
                <a-tag :color="getMethodColor(record.method)">{{ record.method }}</a-tag>
              </template>
              <template v-if="column.key === 'duration'">
                <span>{{ record.duration }}ms</span>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>

      <!-- 系统信息 -->
      <a-col :xs="24" :lg="8">
        <a-card title="系统信息" class="animate-on-enter animate-delay-5" :bordered="false">
          <div class="system-info">
            <div class="info-item">
              <span class="info-label">PHP版本:</span>
              <span class="info-value">{{ systemInfo.php_version }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">服务器:</span>
              <span class="info-value">{{ systemInfo.server_software }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">内存使用:</span>
              <span class="info-value">{{ systemInfo.memory_usage }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">内存峰值:</span>
              <span class="info-value">{{ systemInfo.memory_peak }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">磁盘空间:</span>
              <span class="info-value">{{ systemInfo.disk_free }} / {{ systemInfo.disk_total }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">服务器时间:</span>
              <span class="info-value">{{ systemInfo.server_time }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">时区:</span>
              <span class="info-value">{{ systemInfo.timezone }}</span>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue'
import {
  UserOutlined,
  TeamOutlined,
  FileTextOutlined,
  CrownOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import {
  getStatistics,
  getRecentLogs,
  getUserGrowth,
  getSystemInfo,
  getUserDistribution
} from '@/api/dashboard'

// 页面数据
const statistics = ref({})
const recentLogs = ref([])
const userGrowthData = ref([])
const userDistributionData = ref([])
const systemInfo = ref({})
const loading = ref(false)

// 图表引用
const userGrowthChart = ref(null)
const userDistributionChart = ref(null)

// 表格列配置
const logColumns = [
  {
    title: '操作者',
    dataIndex: 'operator_name',
    key: 'operator_name',
    width: 100
  },
  {
    title: '请求方法',
    dataIndex: 'method',
    key: 'method',
    width: 80
  },
  {
    title: '请求路径',
    dataIndex: 'uri',
    key: 'uri',
    width: 200,
    ellipsis: true
  },
  {
    title: '操作描述',
    dataIndex: 'description',
    key: 'description',
    width: 150,
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'is_success',
    key: 'is_success',
    width: 80
  },
  {
    title: '耗时',
    dataIndex: 'duration',
    key: 'duration',
    width: 80
  },
  {
    title: 'IP地址',
    dataIndex: 'ip',
    key: 'ip',
    width: 120
  },
  {
    title: '操作时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 150
  }
]

// 页面生命周期
onMounted(async () => {
  await loadDashboardData()
  await nextTick()
  initCharts()
})

// 加载仪表盘数据
const loadDashboardData = async () => {
  loading.value = true
  try {
    // 并行加载所有数据
    const [statsRes, logsRes, growthRes, systemRes, distributionRes] = await Promise.all([
      getStatistics(),
      getRecentLogs({ limit: 10 }),
      getUserGrowth(),
      getSystemInfo(),
      getUserDistribution()
    ])

    if (statsRes.code === 200) {
      statistics.value = statsRes.result
    }

    if (logsRes.code === 200) {
      recentLogs.value = logsRes.result
    }

    if (growthRes.code === 200) {
      userGrowthData.value = growthRes.result
    }

    if (systemRes.code === 200) {
      systemInfo.value = systemRes.result
    }

    if (distributionRes.code === 200) {
      userDistributionData.value = distributionRes.result
    }
  } catch (error) {
    message.error('加载数据失败')
    console.error('Dashboard data loading error:', error)
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initCharts = () => {
  initUserGrowthChart()
  initUserDistributionChart()
}

// 初始化用户增长趋势图表
const initUserGrowthChart = () => {
  if (!userGrowthChart.value) return

  const chart = echarts.init(userGrowthChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: userGrowthData.value.map(item => item.label),
      axisLine: {
        lineStyle: {
          color: '#e8e8e8'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#e8e8e8'
        }
      }
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        smooth: true,
        data: userGrowthData.value.map(item => item.count),
        itemStyle: {
          color: '#1890ff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(24, 144, 255, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(24, 144, 255, 0.05)'
              }
            ]
          }
        }
      }
    ]
  }

  chart.setOption(option)

  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化用户分布饼图
const initUserDistributionChart = () => {
  if (!userDistributionChart.value) return

  const chart = echarts.init(userDistributionChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '用户分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        data: userDistributionData.value.map(item => ({
          name: item.name,
          value: item.count
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: false
        }
      }
    ]
  }

  chart.setOption(option)

  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 工具函数
const getGrowthClass = (rate) => {
  if (rate > 0) return 'growth-positive'
  if (rate < 0) return 'growth-negative'
  return 'growth-neutral'
}

const getMethodColor = (method) => {
  const colors = {
    'GET': 'blue',
    'POST': 'green',
    'PUT': 'orange',
    'DELETE': 'red',
    'PATCH': 'purple'
  }
  return colors[method] || 'default'
}
</script>

<style lang="less" scoped>
// 统计网格布局
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 10px;
}

// 统计项目
.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 6px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 2px 0 8px #f5f5f5;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
    transition: left 0.6s ease;
  }

  &:hover {
    background: #f8f9fa;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1), 0 4px 10px rgba(0, 0, 0, 0.05);

    &::before {
      left: 100%;
    }

    .stat-icon {
      transform: scale(1.1) rotate(5deg);
    }

    .stat-value {
      transform: scale(1.05);
    }
  }

  &:active {
    transform: translateY(0);
    transition: transform 0.1s ease;
  }
}

// 统计图标
.stat-icon {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: white;
  flex-shrink: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;

  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    transform: translate(-50%, -50%);
    transition: all 0.3s ease;
  }

  &.user-icon {
    background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  }

  &.active-icon {
    background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  }

  &.log-icon {
    background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
  }

  &.admin-icon {
    background: linear-gradient(135deg, #fa8c16 0%, #ffa940 100%);
  }
}

// 统计内容
.stat-content {
  flex: 1;
  min-width: 0;
}

// 统计数值
.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  line-height: 1.2;
  margin-bottom: 2px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

// 统计标签
.stat-label {
  font-size: 12px;
  color: #8c8c8c;
  font-weight: 400;
  margin-bottom: 2px;
}

// 统计描述
.stat-desc {
  font-size: 11px;
  color: #bfbfbf;
  font-weight: 400;
}

// 趋势指示器
.stat-trend {
  font-size: 11px;
  display: flex;
  align-items: center;
  gap: 2px;
  font-weight: 500;

  &.growth-positive {
    color: #52c41a;
  }

  &.growth-negative {
    color: #ff4d4f;
  }

  &.growth-neutral {
    color: #8c8c8c;
  }
}


.chart-card {
  border-radius: 8px;
  box-shadow: 2px 0 8px #f5f5f5;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  background: #fff;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #1890ff, #40a9ff, #69c0ff);
    transform: scaleX(0);
    transform-origin: left;
    transition: transform 0.3s ease;
  }

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12), 0 6px 20px rgba(0, 0, 0, 0.08);

    &::before {
      transform: scaleX(1);
    }

    :deep(.ant-card-head-title) {
      color: #1890ff;
    }
  }

  :deep(.ant-card-head-title) {
    transition: color 0.3s ease;
  }
}

.chart-container {
  height: 300px;
  width: 100%;
}

.logs-card {
  border-radius: 8px;
  box-shadow: 2px 0 8px #f5f5f5;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  background: #fff;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #722ed1, #9254de, #b37feb);
    transform: scaleX(0);
    transform-origin: left;
    transition: transform 0.3s ease;
  }

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12), 0 6px 20px rgba(0, 0, 0, 0.08);

    &::before {
      transform: scaleX(1);
    }

    :deep(.ant-card-head-title) {
      color: #722ed1;
    }
  }

  :deep(.ant-card-head-title) {
    transition: color 0.3s ease;
  }

  :deep(.ant-table-tbody > tr) {
    transition: all 0.3s ease;

    &:hover {
      background-color: #f8f9fa !important;
      transform: scale(1.01);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
  }
}

.system-info {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    transition: all 0.3s;

    &:hover {
      background-color: #fafafa;
      margin: 0 -20px;
      padding-left: 20px;
      padding-right: 20px;
    }

    &:last-child {
      border-bottom: none;
    }
  }

  .info-label {
    font-size: 14px;
    color: #666;
    font-weight: 400;
  }

  .info-value {
    font-size: 14px;
    color: #333;
    font-weight: 500;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  }
}
</style>